package com.music.controller;

import com.laoxuai.beans.annotation.Autowired;
import com.laoxuai.beans.annotation.Controller;
import com.laoxuai.web.mvc.annotation.RequestMapping;
import com.laoxuai.web.mvc.annotation.ResponseBody;
import com.music.constant.Constant;
import com.music.dao.UserDao;
import com.music.pojo.User;
import com.music.service.UserService;
import com.music.util.Result;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.base.Captcha;
import com.wf.captcha.utils.CaptchaUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {
    @Autowired
    UserService userServiceImpl;

    @RequestMapping("/admin/captcha")
    @ResponseBody
    public Result captcha(HttpServletRequest request) throws Exception {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        captcha.setLen(2);
        String result = captcha.text();
        request.getSession().setAttribute(Constant.CAPTCHA_CODE, result);
        return Result.success("success", captcha.toBase64());
    }

    @RequestMapping("/admin/login")
    @ResponseBody
    public Result login(String username, String password, String validateCode, HttpServletRequest request,HttpServletResponse response) {
        String vercode = (String) request.getSession().getAttribute(Constant.CAPTCHA_CODE);
        System.out.println("validateCode:" + validateCode);
        System.out.println("vercode:" + vercode);
        if (!vercode.equals(validateCode)) {
            return Result.failed("验证码错误");
        }
        User user = userServiceImpl.getUserByName(username);
        if (user == null) {
            return Result.failed("用户不存在");
        }
        user = userServiceImpl.modifyLogin(username, password);
        if (user == null) {
            return Result.failed("用户名或密码不正确");
        }
        System.out.println(user.getUserId());
        request.getSession().setAttribute("user",user);
        return Result.success("操作成功", user);
    }

    @RequestMapping("/admin/logout")
    public Result logOut(HttpServletRequest request){
        request.getSession().invalidate();
        return Result.success("操作成功");
    }
}
